package com.touzi.listeners;


import com.touzi.constants.DbCons;
import com.touzi.utils.DateUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;

public class MyServletContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            String resource = "mybatisconfig/mybatis-config.xml";
            InputStream inputStream = null;
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            sce.getServletContext().setAttribute(DbCons.DB_FACTORY, sqlSessionFactory);

            //每隔一小时扫描分红计划表,实际是在整点01分开始分红
            new Timer().scheduleAtFixedRate(new FenhongTimerTask(sqlSessionFactory), DateUtils.getNextHour().getTime(), 1000 * 60 * 60);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
